<template>
  <div >
    <!-- 搜索与操作按钮 -->
    <div class="card" style="margin-bottom: 5px" >
      <el-input v-model="data.searchName" prefix-icon="Search" style="width: 240px; margin-right: 10px" placeholder="请输入商品名称查询"></el-input>
      <el-button type="info" plain @click="load">查询</el-button>
      <el-button type="warning" plain style="margin: 0 10px" @click="reset">重置</el-button>
    </div>

    <!-- 商品卡片列表 -->
    <div class="card-container">
      <el-card
          v-for="(goods, index) in data.tableData"
          :key="index"
          :style="{ width: '18%', margin: '1%', minWidth: '290px' }"
          shadow="hover"
          class="goods-card"
      >
        <div class="card-content">
          <img
              :src="goods.image"
              class="goods-image"
              @click="openImageViewer(goods.image)"
          />
          <div class="goods-info">
            <div class="goods-header">
              <span class="goods-title">{{ goods.goodsName }}</span>
              <el-tag
                  :type="goods.status === 0 ? 'success' : 'danger'"
                  effect="light"
                  size="small"
              >
                {{ getStatusText(goods.status) }}
              </el-tag>
            </div>

            <el-tooltip
                effect="dark"
                :content="goods.description"
                placement="top-start"
            >
              <div class="goods-description">
                {{ shortDescription(goods.description) }}...
              </div>
            </el-tooltip>

            <div class="goods-meta">
              <div class="meta-item">
                <el-icon><PriceTag /></el-icon>
                <span class="highlight">{{ goods.points }} 积分</span>
              </div>
              <div class="meta-item">
                <el-icon><Box /></el-icon>
                <span>库存 {{ goods.stock }}</span>
              </div>
            </div>

            <el-button
                type="primary"
                class="exchange-btn"
                v-if="goods.status === 0 && goods.stock > 0"
                @click="exchange(goods)"
            >
              <el-icon><SoldOut /></el-icon>
              立即兑换
            </el-button>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 分页 -->
    <div class="card" v-if="data.total">
      <el-pagination @current-change="load" background layout="prev, pager, next" :page-size="data.pageSize" v-model:current-page="data.pageNum" :total="data.total"/>
    </div>

    <!-- 兑换确认对话框 -->
    <el-dialog title="确认兑换" v-model="data.exchangeDialogVisible" width="40%">
      <el-form ref="exchangeFormRef" :model="data.exchangeForm" label-width="100px" :rules="rules">
        <el-form-item label="商品名称">
          <el-input v-model="data.selectedGoods.goodsName" disabled></el-input>
        </el-form-item>
        <el-form-item label="所需积分">
          <el-input v-model="data.selectedGoods.points" disabled></el-input>
        </el-form-item>
        <el-form-item label="收件人姓名" prop="recipientName">
          <el-input v-model="data.exchangeForm.recipientName" placeholder="请输入收件人姓名"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="data.exchangeForm.contactPhone" placeholder="请输入联系电话"></el-input>
        </el-form-item>
        <el-form-item label="收货地址" prop="shippingAddress">
          <el-input v-model="data.exchangeForm.shippingAddress" placeholder="请输入收货地址"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.exchangeDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="validateAndConfirmExchange">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 图片查看器 -->
    <el-image-viewer
        v-if="data.showImageViewer"
        :url-list="[data.currentImage]"
        @close="data.showImageViewer = false"
    />
  </div>
</template>

<script setup>
import { reactive, watch, ref } from "vue";
import request from "@/utils/request.js";
import { ElMessage } from "element-plus";
import {Box, PriceTag, SoldOut} from "@element-plus/icons-vue";

const baseUrl = import.meta.env.VITE_BASE_URL;

const data = reactive({
  formVisible: false,
  exchangeDialogVisible: false,
  tableData: [],
  pageNum: 1,
  pageSize: 10,
  total: 0,
  searchName: null,
  selectedGoods: {}, // 添加 selectedGoods 属性
  exchangeForm: {
    recipientName: '',
    contactPhone: '',
    shippingAddress: ''
  },
  showImageViewer: false,
  currentImage: ''
});

// 表单验证规则
const rules = {
  recipientName: [
    { required: true, message: '请输入收件人姓名', trigger: 'blur' }
  ],
  contactPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  shippingAddress: [
    { required: true, message: '请输入收货地址', trigger: 'blur' }
  ]
};

const exchangeFormRef = ref(null);

// 加载商品列表
const load = () => {
  request.get('/pointsGoods/page', {
    params: {
      pageNum: data.pageNum,
      pageSize: data.pageSize,
      searchName: data.searchName
    }
  }).then(res => {
    if (res.code === '200') {
      data.tableData = res.data.list || [];
      data.total = res.data.total;
    }
  })
};

// 截断描述
const shortDescription = (description) => {
  if (description.length > 30) {
    return description.substring(0, 30);
  }
  return description;
};

// 获取状态文本
const getStatusText = (status) => {
  return status === 0 ? '上架' : '下架';
};

// 获取状态颜色
const getStatusColor = (status) => {
  return status === 0 ? '#f0f9eb' : '#fef0f0'; // 上架绿色背景，下架红色背景
};

// 重置搜索条件
const reset = () => {
  data.searchName = null;
  load();
};

// 打开兑换确认对话框
const exchange = (goods) => {
  data.selectedGoods = goods;
  data.exchangeForm.recipientName = '';
  data.exchangeForm.contactPhone = '';
  data.exchangeForm.shippingAddress = '';
  data.exchangeDialogVisible = true;
};

// 确认兑换前进行表单验证
const validateAndConfirmExchange = () => {
  exchangeFormRef.value.validate((valid) => {
    if (valid) {
      confirmExchange();
    } else {
      console.log('表单验证失败');
      return false;
    }
  });
};

// 确认兑换
const confirmExchange = async () => {
  try {
    const pointsOrderVo = {
      goodsId: data.selectedGoods.id,
      quantity: 1,
      recipientName: data.exchangeForm.recipientName,
      contactPhone: data.exchangeForm.contactPhone,
      shippingAddress: data.exchangeForm.shippingAddress
    };

    const res = await request.post(`/pointsGoods/exchange/${data.selectedGoods.id}`, pointsOrderVo);
    if (res.code === '200') {
      ElMessage.success('兑换成功');
      data.exchangeDialogVisible = false;
      load(); // 刷新商品列表
    } else {
      ElMessage.error(res.msg);
    }
  } catch (error) {
    console.error('Failed to exchange goods:', error);
    ElMessage.error('兑换失败，请稍后再试');
  }
};

// 打开图片查看器
const openImageViewer = (imageUrl) => {
  data.currentImage = imageUrl;
  data.showImageViewer = true;
};

// 初始化加载商品列表
load();
</script>

<style scoped>
.card-container {
  display: grid;
  /* 修改1：使用固定列数 + 更精确的宽度计算 */
  grid-template-columns: repeat(5, minmax(0, 1fr));
  /* 修改2：缩小间距 */
  gap: 12px;
  margin: 0;
}

.goods-card {
  /* 修改3：强制撑满网格单元格 */
  width: 100% !important;
  /* 修改4：移除所有外边距 */
  margin: 0 !important;
  /* 修改5：限制卡片最小宽度 */
  min-width: 240px;
  transition: all 0.3s;
}

/* 响应式适配调整 */
@media (max-width: 1920px) {
  .card-container {
    grid-template-columns: repeat(5, minmax(0, 1fr));
  }
}

@media (max-width: 1600px) {
  .card-container {
    grid-template-columns: repeat(4, minmax(0, 1fr));
  }
}

@media (max-width: 1280px) {
  .card-container {
    grid-template-columns: repeat(3, minmax(0, 1fr));
  }
}

@media (max-width: 768px) {
  .card-container {
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 8px;
  }
}

.goods-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.12);
}

.card-content {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.goods-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
  border-radius: 8px 8px 0 0;
  cursor: pointer;
  transition: transform 0.3s;
}

.goods-image:hover {
  transform: scale(1.03);
}

.goods-info {
  padding: 16px;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.goods-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start; /* 修改为顶部对齐 */
  margin-bottom: 12px;
  min-height: 44px; /* 固定最小高度 */
}

.goods-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  flex: 1;
  margin-right: 8px;
  /* 新增文字截断 */
  display: -webkit-box;
  -webkit-line-clamp: 2; /* 最多显示2行 */
  -webkit-box-orient: vertical;
  overflow: hidden;
  line-height: 1.3; /* 优化行高 */
}
.goods-header .el-tag {
  flex-shrink: 0; /* 禁止标签收缩 */
  margin-left: 8px;
  margin-top: 2px; /* 微调对齐 */
}
.goods-description {
  color: #606266;
  font-size: 13px;
  line-height: 1.5;
  margin-bottom: 16px;
  flex: 1;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.goods-meta {
  margin-top: auto;
  font-size: 14px;
}

.meta-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  color: #909399;
}

.meta-item .el-icon {
  margin-right: 8px;
  font-size: 16px;
}

.highlight {
  color: #409EFF;
  font-weight: 500;
}

.exchange-btn {
  width: 100%;
  margin-top: 16px;
  padding: 12px;
  border-radius: 8px;
  letter-spacing: 0.5px;
  transition: all 0.2s;
}

.exchange-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
}
</style>
